<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="lib/layui/css/layui.css">
    <script src="lib/layui/layui.js"></script>
    <script src="lib/jquery-1.12.4.js"></script>
    <script type="text/html" id="barDemo">
        <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="edit">编辑</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    </script>

    <script type="text/html" id="singlebar">
        <div class="layui-btn-container">
            <button class="layui-btn layui-btn-sm layui-btn-warm" lay-event="addSingleSpec">单规格新增</button>
        </div>
    </script>

    <script type="text/html" id="multibar">
        <div class="layui-btn-container">
            <button class="layui-btn layui-btn-sm layui-btn-warm" lay-event="addMultiSpec">多规格新增</button>
        </div>
    </script>
</head>
<body>
<fieldset class="layui-elem-field layui-field-title">
    <legend>商品规格管理</legend>
</fieldset>
<table class="layui-hide" id="single" lay-filter="single"></table>

<table class="layui-hide" id="multi" lay-filter="multi"></table>
</body>
<script>
    layui.use(['table','form','layer','jquery'], function () {
        var table = layui.table,
            form = layui.form,
            $ = layui.jquery,
            layer = layui.layer;
        table.render({
            elem: '#single'
            , url: ' xp/goods/singleSpec'
            , toolbar: '#singlebar'
            , height: 300
            // ,cellMinWidth: 80 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
            ,parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": 0, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.code,//解析数据长度
                    "data": res.obj//解析数据列表
                };
            }
            , cols: [[
                 {
                     field: 'specificationName',
                     title: '规格名称',
                     align: "center",
                     width: 300
                 }
                ,{
                    fixed: 'right',
                    title: '操作',
                    width: 200,
                    toolbar: '#barDemo',
                    align: "center"
                }

            ]]
        });

        var tb = table.render({
            elem: '#multi'
            , url: ' xp/goods/multiSpec'
            , toolbar: '#multibar'
            , height: 300
            // ,cellMinWidth: 80 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
            ,parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": 0, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.code,//解析数据长度
                    "data": res.obj//解析数据列表
                };
            }
            , cols: [[
                {
                    field: 'specificationName',
                    title: '规格名称',
                    align: "center",
                    width: 300
                }
                ,{
                    fixed: 'right',
                    title: '操作',
                    width: 200,
                    toolbar: '#barDemo',
                    align: "center"
                }

            ]]
        });

        table.on('toolbar(single)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id);
            var data = checkStatus.data; //获取选中的数据
            if(obj.event=='addSingleSpec'){
                layer.open({
                    type: 1
                    , title: '系统提示' //不显示标题栏
                    , area: ['400px', '200px']
                    , shade: 0.3
                    , btnAlign: 'c'
                    , id: 'LAY_layuipro' //设定一个id，防止重复弹出
                    , content: '<form class="layui-form"><div class="layui-form-item" id="s" style="margin-top: 20px">\n' +
                        '                        <label class="layui-form-label"><span style="color: red">*</span>单规格</label>\n' +
                        '                        <div class="layui-input-inline">\n' +
                        '                            <input type="text" name="s_module" id="only" lay-verify="single"  placeholder="请输入规格名称"\n' +
                        '                                   autocomplete="off" class="layui-input">\n' +
                        '                        </div>\n' +
                        '                    </div>' +
                        '<div class="layui-form-item">\n' +
                        '                        <div class="layui-inline"\n' +
                        '                             style="margin-top: 20px;display: flex;justify-content: center;align-items: center">\n' +
                        '                            <button type="button" lay-submit="" lay-filter="saveSingle" class="layui-btn layui-btn-normal">\n' +
                        '                                保存\n' +
                        '                            </button>\n' +
                        '                            <button type="button" class="layui-btn layui-btn-primary" onclick="cancel()">取消</button>\n' +
                        '                        </div>\n' +
                        '                    </div>' +
                        '</form>'
                });
            }
        });

        table.on('toolbar(multi)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id);
            var data = checkStatus.data; //获取选中的数据
            if(obj.event=='addMultiSpec'){
                layer.open({
                    type: 1
                    , title: '系统提示' //不显示标题栏
                    , area: ['600px', '400px']
                    , shade: 0.3
                    , btnAlign: 'c'
                    , id: 'LAY_layuipro' //设定一个id，防止重复弹出
                    , content: '<form class="layui-form" lay-filter="multi"><div class="layui-form-item" id="content" style="margin-top: 20px">\n' +
                        '                        <div class="layui-inline" style="margin-bottom: 10px">\n' +
                        '                            <label class="layui-form-label"><span style="color: red">*</span>基本单位：</label>\n' +
                        '                            <div class="layui-input-inline">\n' +
                        '                                <input type="text" name="m_module" id="basic" onblur="syn()" lay-verify="m_spec"\n' +
                        '                                       placeholder="请输入基本规格名称" autocomplete="off" class="layui-input">\n' +
                        '                            </div>\n' +
                        '                        </div>\n' +
                        '                        <div class="layui-inline">\n' +
                        '                            <button type="button" class="layui-btn layui-btn-primary" id="add" onclick="addUnit()"><i\n' +
                        '                                    class="layui-icon"></i>增加单位\n' +
                        '                            </button>\n' +
                        '                        </div>\n' +
                        '                        <div class="layui-inline">\n' +
                        '                            <i class="layui-icon layui-icon-about"\n' +
                        '                               style="font-size: 30px; color: #1E9FFF;margin-left: 10px" id="tip"></i>\n' +
                        '                        </div>\n' +
                        '                    </div>\n' +
                        '                    <div class="layui-form-item">\n' +
                        '                        <div class="layui-inline"\n' +
                        '                             style="margin-top: 20px;display: flex;justify-content: center;align-items: center">\n' +
                        '                            <button type="button" lay-submit="" lay-filter="saveMulti" onclick="Multi()" class="layui-btn layui-btn-normal">\n' +
                        '                                保存\n' +
                        '                            </button>\n' +
                        '                            <button type="button" class="layui-btn layui-btn-primary" onclick="cancel()">取消</button>\n' +
                        '                        </div>\n' +
                        '                    </div></form>'
                });

            }

        });

        form.verify({
            single: function (value) {
                if (!value) {
                    return '请输入规格'
                }
                var message = '';
                $.ajax({
                    url : ' xp/spec/verify',
                    data: {'name': value},
                    type: 'post',
                    async: false,
                    dataType:'json',
                    success: function (data) {
                        if(data.obj==null){
                            message = ''
                        }else{
                            message= '该规格已存在'
                        }
                    },
                    error: function () {
                        return false;
                    }
                });
                return message;
            },
            m_spec: function (value) {
                if (!value) {
                    return '请输入规格'
                }
                var number = $(".layui-form-item .layui-inline").find(".layui-input-inline:first").length;
                if(number<3){
                    return '新增失败，单位级数须大于1'
                }
            },
            parent: function (value) {
                if (!value) {
                    return '父级单位不能为空,换算率应为数字且大于0!'
                }
            },
            fu: function (value) {
                var reg = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
                if (!value) {
                    return '副单位不能为空，换算率应为数字且大于0!'
                } else if (!(reg.test(value))) {
                    return '换算率应为数字且大于0！'
                }
            }
        });


        form.on("submit(saveSingle)",function (data) {
            $.ajax({
                url: ' xp/spec/add',
                data: {'name': $("#only").val(),'type': 0},
                dataType: 'json',
                type: "post",
                async: false,
                success: function (data) {
                    if(data.obj>0){
                        layer.msg("新增成功",{icon:1});
                    }
                    setTimeout( function(){
                        layer.closeAll();
                    }, 2000);//延迟5000毫秒

                },
                complete: function () {
                    table.reload('single');
                    //parent.layui.table.reload('single');
                    return false;
                },
                error: function () {
                    layer.msg("新增出错，请稍后再试",{icon:2});
                    return false;
                }
            });
            return false;
        });
        table.on('tool(single)', function (obj) {
            var data = obj.data;
            if (obj.event === 'del') {
                beforeDel(data.specificationId,data.id);
                obj.del();
            }else if(obj.event === 'edit'){
                layer.open({
                    type: 1
                    , title: '规格修改' //不显示标题栏
                    , area: ['400px', '200px']
                    , shade: 0.3
                    , btnAlign: 'c'
                    , id: 'LAY_layuipro' //设定一个id，防止重复弹出
                    , content: '<form class="layui-form"><div class="layui-form-item" id="s" style="margin-top: 20px">\n' +
                        '                        <label class="layui-form-label"><span style="color: red">*</span>单规格</label>\n' +
                        '                        <div class="layui-input-inline">\n' +
                        '                            <input type="text" name="s_module" id="only" lay-verify="single"  placeholder="请输入规格名称"\n' +
                        '                                   autocomplete="off" class="layui-input">\n' +
                        '                            <input type="hidden" id="specId">\n'+
                        '                        </div>\n' +
                        '                    </div>' +
                        '<div class="layui-form-item">\n' +
                        '                        <div class="layui-inline"\n' +
                        '                             style="margin-top: 20px;display: flex;justify-content: center;align-items: center">\n' +
                        '                            <button type="button" onclick="updateSingle()" class="layui-btn layui-btn-normal">\n' +
                        '                                保存\n' +
                        '                            </button>\n' +
                        '                            <button type="button" class="layui-btn layui-btn-primary" onclick="cancel()">取消</button>\n' +
                        '                        </div>\n' +
                        '                    </div>' +
                        '</form>'
                    , success: function(layero, index){
                        edit(data.id);
                    }
                })
            }
        });

        table.on('tool(multi)', function (obj) {
            var data = obj.data;
            //console.log(data);
            if (obj.event === 'del') {
                beforeDel(data.specificationId,data.id);
                obj.del();
            }else if(obj.event === 'edit'){
                layer.open({
                    type: 2
                    , title: '多规格内容修改'
                    , shade: 0.3
                    , btnAlign: 'c'
                    , area: ['600px', '350px']
                    , content: 'MultiSpecUpdate.html?id='+data.id
                })
            }
        });


    });
    function beforeDel(sid,id){
        var flag = confirm("删除的计量单位将不能恢复，请确认是否删除？");
        console.log(flag);
       if(flag) {
            $.ajax({
                url : ' xp/spec/beforeDel',
                data: {'specificationId': sid},
                type: 'get',
                dataType: 'json',
                async: false,
                success: function (data) {
                    if(data.obj==''){
                        $.ajax({
                            url : 'xp/spec/delSpec',
                            data: {'id': id},
                            type: 'get',
                            dataType: 'json',
                            async: false,
                            success: function (result) {
                                if(result.obj>0){
                                    layer.msg('删除成功',{icon: 1})
                                }else{
                                    layer.msg('删除失败',{icon: 1})
                                }
                                return false
                            },
                            error: function () {
                                layer.msg('删除失败',{icon: 2})
                            }

                        })
                    }else{
                        layer.msg('该单位已被使用，不能删除',{icon: 2})
                    }
                }
            })
        }
    }

    function edit(obj) {
        $.ajax({
            url : ' xp/spec/getOne',
            data: {"id": obj},
            dataType: 'json',
            type: 'get',
            success: function (data) {
                if(data.obj!=''){
                    $("#only").val(data.obj.specificationName);
                    $("#specId").val(data.obj.id);
                    $('input').select()
                }
            }
        })
    }
    function updateSingle() {
        if($("#only").val()==''){
            layer.msg("规格内容不能为空",{icon: 2})
        }else{
            $.ajax({
                url : 'xp/spec/verify',
                data: {'name': $("#only").val()},
                type: 'post',
                async: false,
                dataType:'json',
                success: function (data) {
                    if(data.obj==null || data.obj == $("#only").val()){
                        $.ajax({
                            url : 'xp/spec/updateSingle',
                            data: {'name': $("#only").val(),'id':$("#specId").val()},
                            dataType: 'json',
                            type: 'post',
                            success: function (data) {
                                if(data.obj>0){
                                    layer.closeAll(); //关闭所有的iframe层
                                }
                            },
                            complete: function () {
                                layer.msg("修改成功",{icon:1});
                                //parent.layui.table.reload('single');
                                layui.table.reload('single');
                                return false;
                            },
                            error: function () {
                                layer.msg("修改失败，请稍后再试",{icon:7});
                                return false;
                            }
                        })
                    }else{
                        layer.msg("该规格已存在",{icon: 2})
                    }

                },
                error: function () {
                    return false;
                }
            });
        }


    }
    function cancel() {
        $('#save').attr('disabled', 'disabled');
        layer.closeAll();
    }

    function fan(obj) {
        obj.parentNode.parentNode.parentNode.removeChild(obj.parentNode.parentNode);
        order();
    }
    //多级单位同步
    function syn(){
        var value = $("#basic").val();
        $(".index").html(value);
    }
    //多级输入框排序
    function order() {
        var number = $(".layui-form-item .layui-inline").find("label:first");
        for (var j = 1; j < number.length; j++) {
            number.eq(j).text(j + "级父单位：");
        }
    }

    var tips = "基本单位应为最小度量单位";
    var tip_index = 0;
    jQuery(document).on('mouseenter', '#tip', function () {
        tip_index = layer.tips(tips, '#tip', {time: 0, tips: [2, '#3595CC'], area: ['180px', '40px']});
    }).on('mouseleave', '#tip', function () {
        layer.close(tip_index);
    });

    function addUnit() {
        var html = $("#content");
        var char = "<div class=\"layui-form-item\">\n" +
            "                    <div class=\"layui-inline\">\n" +
            "                        <label class=\"layui-form-label \"></label>\n" +
            "                        <div class=\"layui-input-inline\">\n" +
            "                            <input type=\"text\" lay-verify=\"parent\" placeholder=\"\" autocomplete=\"off\" class=\"layui-input unit\">\n" +
            "                        </div>\n" +
            "                    </div>\n" +
            "                    <div class=\"layui-inline\">\n" +
            "                      &nbsp;=&nbsp;\n" +
            "                    </div>\n" +
            "                    <div class=\"layui-inline\">\n" +
            "                        <div class=\"layui-input-inline\" style=\"width: 100px;\">\n" +
            "                            <input type=\"text\" lay-verify=\"fu\" autocomplete=\"off\" class=\"layui-input base\">\n" +
            "                        </div>\n" +
            "                    </div>\n" +
            "                    <div class=\"layui-inline\" style='width: 15px'>\n" +
            "                        <span class='index'></span>\n" +
            "                    </div>\n" +
            "                    <div class=\"layui-inline\">\n" +
            "                        <button type=\"button\" class=\"layui-btn layui-btn-primary layui-btn-sm\" onclick='fan(this)'><i class=\"layui-icon\"></i></button>\n" +
            "                    </div>\n" +
            "                </div>";

        html.append(char);
        var value = $("#basic").val();
        $(".index").html(value);
        order();
    }
    function Multi() {
        var basic = $("#basic").val();
        var parentName = [];
        var parentBase = [];
        var base = $(".base");
        var unit = $('.unit');
        var result = $(".unit:last").val();
        for(var i=0;i<unit.length;i++){
            parentName.push(unit.eq(i).val());
            parentBase.push(base.eq(i).val());
        }
        var result2 = '';
        for(var j=0;j<unit.length;j++){
            if(j==unit.length-1){
                result2 = result2+parentName[j];
            }else{
                result2= result2+parentName[j] +'-';
            }
        }
        var result3 = '';
        for(var k=0;k<base.length;k++){
            if(k==base.length-1){
                result3 = result3+parentBase[k];
            }else{
                result3 = result3+parentBase[k]+ '-';
            }

        }
        result3 = result3 + ')';
        result = result +'：'+ basic+'-'+result2 + '(1-'+result3;
        var msg = '';
        $.ajax({
            url : ' xp/spec/verify',
            data: {'name':result},
            type: 'post',
            async: false,
            dataType: 'json',
            success: function (data) {
                if(data.obj==null){
                    msg = ''
                }else{
                    msg = '该规格已存在';
                    layer.msg(msg,{icon:5});
                }
                return false
            },
            error: function () {
                layer.msg('出现错误',{icon:2})
            }
        });
        if(!msg){
            $.ajax({
                url: ' xp/spec/add',
                data: {'name': result,'type': 1},
                dataType: 'json',
                type: "post",
                async: false,
                success: function (data) {
                    if(data.obj>0){
                        layer.closeAll(); //关闭所有的iframe层
                    }
                },
                complete: function () {
                    layer.msg("新增成功",{icon:1});
                    layui.table.reload('multi');
                    return false;
                },
                error: function () {
                    layer.msg("新增出错，请稍后再试",{icon:7});
                    return false;
                }
            });
        }
    }

    function reload(id) {
        layui.table.reload(id);
    }
</script>
</html>